<template>
    <div>
        <section class="main" v-cloak>
            <input class="toggle-all" type="checkbox" @click="allDone" v-model="allCheck">
            <ul class="todo-list">
                <li class="todo" v-for="(item,index) in todoList" :key="index"
                :class="{
                completed: item.isCheck,
                editing: isShow == index
                }">
                <!-- completed：是否完成-->
                <!-- editing：是否显示编辑input框 -->
                    <div class="view">
                        <input class="toggle" type="checkbox" v-model="item.isCheck" @click="changeCheck">
                        <label @dblclick="editItem(item,index)">{{ item.text }}</label>
                        <button class="destroy" @click="deleteItem(index)"></button>
                    </div>
                    <input class="edit" 
                    type="text"
                    v-focus
                    v-model="editText"
                    @blur="doneEdit(index)"
                    @keyup.enter="$event.target.blur"
                    @keyup.esc="cancelEdit()">
                </li>
            </ul>
        </section>
    </div>
</template>

<script>
import { mapState, mapActions, mapMutations } from "vuex";
import { setAllDone , getAllDone} from "@/utils/localStorageTodo";
export default {
  data() {
    return {
      isShow: null,
      editText: "",
      allCheck:false
    };
  },
  mounted() {
      this.allCheck = this.allChecked
  },
  methods: {
    ...mapActions("todolist", ["updateTodoList", "setChecked","deleteTodoList","setAllChecked"]),
    editItem(item, index) {
      //双击编辑
      this.isShow = index;
      this.editText = item.text;
    },
    doneEdit(index) {
      //完成编辑
      this.updateTodoList({
        text: this.editText,
        index
      });
      this.isShow = null;
    },
    cancelEdit() {
      //取消编辑
      this.isShow = null;
    },
    deleteItem(index) {
      //删除
      this.deleteTodoList(index);
    },
    allDone() {
      //全选反选
      this.setChecked(this.allCheck);
    },
    changeCheck() {
        console.log(this.todoList.filter(v=>v.isCheck))
        this.setAllChecked()
    }
  },
  computed: {
    ...mapState("todolist", ["todoList","allChecked"])
  },
  directives: {
    focus(el) {
      el.focus();
    }
  },
  watch: {
    allChecked: {
      handler(newVal) {
        setAllDone(newVal);
      }
    }
  }
};
</script>

<style scoped src="../assets/style/todolist.css">
</style>